package org.kiwi.util.mapping.converter;

import ma.glasnost.orika.metadata.Type;
import org.kiwi.util.mapping.EnhancedBidirectionalConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;

/**
 * Created by jack08.liu on 2016/8/11.
 */
public class ByteArrayToStringConverter extends EnhancedBidirectionalConverter<byte[], String> {

    private static final Logger LOGGER = LoggerFactory.getLogger(ByteArrayToStringConverter.class);

    private final static String CHARACTER_ENCODE = "ISO-8859-1";

    @Override
    public String convertTo(byte[] source, Type<String> destinationType) {
        try {
            String str = new String(source, CHARACTER_ENCODE);
            return str;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

    @Override
    public byte[] convertFrom(String source, Type<byte[]> destinationType) {
        try {
            byte[] bytes = source.getBytes(CHARACTER_ENCODE);
            return bytes;
        } catch (UnsupportedEncodingException e) {
            LOGGER.error(e.getMessage(), e);
        }
        return null;
    }

}
